package jgl.vajra.kingkong.part.vehicle.pop;

import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import com.orhanobut.logger.Logger;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.MarketPriceBean;
import jgl.vajra.kingkong.bean.RewardBean;
import jgl.vajra.kingkong.databinding.PopRewardBinding;
import jgl.vajra.kingkong.utils.RandomUtils;
import jgl.vajra.kingkong.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.kingkong.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.kingkong.widget.manager.RxJavaHttpManager;
import jgl.vajra.kingkong.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

public class RewardPop implements BaseBindingItemPresenter<RewardBean> {
    private final MarketPriceBean marketPriceBean;
    private WeakReference<FragmentActivity> activityWeakReference;
    private PopupWindow menuPop;
    private View mPopRootView;
    private PopRewardBinding mBinding;
    private List<RewardBean> listReward = new ArrayList<>();
    private SingleTypeBindingAdapter adapter;
    private RewardBean itemData;

    private String authorization;
    private String price;
    private String order;
    private RewardListener listener;
    private String amount;

    public RewardPop(FragmentActivity activity, MarketPriceBean marketPriceBean, String authorization, String price, String order) {
        activityWeakReference = new WeakReference<>(activity);
        this.marketPriceBean = marketPriceBean;
        this.authorization = authorization;
        this.price = price;
        this.order = order;
    }

    private void initPopupWindow() {
        mPopRootView = View.inflate(UIUtils.getContext(), R.layout.pop_reward, null);
        mBinding = DataBindingUtil.bind(mPopRootView);
        if (mBinding != null)
            mBinding.setView(this);

        menuPop = new PopupWindow(mPopRootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        menuPop.setOutsideTouchable(false);
        menuPop.setBackgroundDrawable(new BitmapDrawable());
        menuPop.setFocusable(true);// 点击空白处时，隐藏掉pop窗口
        menuPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Logger.d("------onDismiss");
                //popupwindow消失的时候恢复成原来的透明度
                // backgroundAlpha(R.color.gray_f8);
                backgroundAlpha(1f);

            }
        });


        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new GridLayoutManager(UIUtils.getContext(), 4));
        adapter = new SingleTypeBindingAdapter(UIUtils.getContext(), listReward, R.layout.item_pop_reward);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);


        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
        map.put("amount", price);

        RetrofitJsonManager.getInstance().getApiService().getPriceData(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<List<String>>(true, null) {
                    @Override
                    public void _onNext(List<String> data) {

                        for (int i = 0; i < data.size(); i++) {
                            RewardBean rewardBean = new RewardBean();
                            rewardBean.name = data.get(i);
                            rewardBean.isCustom = false;
                            listReward.add(rewardBean);
                        }

                        RewardBean rewardBean = new RewardBean();
                        rewardBean.name = "自定义\n金额";
                        rewardBean.isCustom = true;
                        listReward.add(rewardBean);

                        adapter.refresh();
                    }
                });
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        if (activityWeakReference.get() == null) return;
        if (activityWeakReference != null) {
            WindowManager.LayoutParams lp = activityWeakReference.get().getWindow().getAttributes();
            lp.alpha = bgAlpha; //0.0-1.0
            activityWeakReference.get().getWindow().setAttributes(lp);
        }
    }

    public void showPopupWindow(View v) {
        if (menuPop == null)
            initPopupWindow();
        int[] location = new int[2];
        v.getLocationOnScreen(location);  //获取控件的位置坐标
        //获取自身的长宽高
        mPopRootView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        //backgroundAlpha(R.color.titleBackgroundColor);
        backgroundAlpha(0.8f);

        menuPop.showAtLocation(v, Gravity.BOTTOM, 0, 0);  //显示指定控件的上方

    }

    public boolean isShowing() {
        return menuPop != null && menuPop.isShowing();
    }

    public void dismiss() {
        if (isShowing()) {
            menuPop.dismiss();
        }
    }

    //确定
    public void onDetermine() {
        if (itemData == null) {
            ToastUtils.showShort("请选择或输入打赏金额");
            return;
        }

        if (itemData.isCustom) {
            amount = mBinding.etAmountMoney.getText().toString().trim();

            if (Integer.parseInt(amount) < Integer.parseInt(listReward.get(0).name)) {
                ToastUtils.showShort("输入的打赏金额最低" + listReward.get(0).name + "元");
                return;
            }

            double currentPrice = Double.parseDouble(price) + Double.parseDouble(amount);
            if (Double.parseDouble(marketPriceBean.highestPrice) < currentPrice) {
                ToastUtils.showShort("打赏总价不能高于市场价格" + marketPriceBean.highestPrice);
                return;
            }

        } else {
            double currentPrice = Double.parseDouble(price) + Double.parseDouble(itemData.name);
            if (Double.parseDouble(marketPriceBean.highestPrice) < currentPrice) {
                ToastUtils.showShort("打赏总价不能高于市场价格" + marketPriceBean.highestPrice);
                return;
            }

            amount = itemData.name;
        }

        if (TextUtils.isEmpty(amount)) {
            ToastUtils.showShort("请选择或输入打赏金额");
            return;
        }

        BigDecimal bgPrice = new BigDecimal(price);
        BigDecimal bgAddAmount = new BigDecimal(amount);
        amount = bgPrice.add(bgAddAmount).toString();

        Map<String, Object> map = new HashMap<>();
        map.put("authorization", authorization);
        map.put("orderId", order);
        map.put("amount", amount);

        RetrofitJsonManager.getInstance().getApiService().rewardOrder(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(true, null) {
                    @Override
                    public void _onNext(String data) {
                        ToastUtils.showShort("打赏成功");
                        dismiss();

                        if (listener != null) {
                            listener.onDetermine(amount);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                        ToastUtils.showShort(errorMessage);
                    }
                });
    }

    @Override
    public void onItemClick(int position, RewardBean itemData) {
        this.itemData = itemData;
        if (itemData.isClick)
            return;
        for (RewardBean item : listReward) {
            item.isClick = false;
        }
        listReward.get(position).isClick = true;
        adapter.refresh();

        mBinding.etAmountMoney.setText("");
        mBinding.etAmountMoney.setVisibility(itemData.isCustom ? View.VISIBLE : View.GONE);
    }

    public void setRewardListener(RewardListener listener) {
        this.listener = listener;

    }

    public interface RewardListener {
        void onDetermine(String amount);
    }
}
